package com.xd.clap.services.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xd.clap.entity.User;
import com.xd.clap.entity.response.Result;
import com.xd.clap.mapper.UserMapper;
import com.xd.clap.services.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper um;

    @Override
    public Result getUser(String phone) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, phone);
        User user = um.selectOne(queryWrapper);
        if (user == null) {
            User insertUser = new User();
            insertUser.setPhone(phone);
            int inserted = um.insert(insertUser);
            if (inserted > 0) {
                LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
                queryWrapper.eq(User::getPhone, phone);
                User newUser = um.selectOne(query);
                return Result.success(newUser, "success");
            } else {
                return Result.fail(0, "fail");
            }
        }
        return Result.success(user, "success");
    }

    @Override
    public Result updateUser(User user) {
        if (StringUtils.isBlank(user.getPhone())) {
            return Result.fail(0, "fail");
        }
        QueryWrapper<User> updateQuery = new QueryWrapper<>();
        updateQuery.eq("phone", user.getPhone());
        int updated = um.update(user, updateQuery);
        if (updated > 0) {
            return Result.success(null, "success");
        } else {
            return Result.fail(0, "fail");
        }
    }
}
